﻿using System;
using System.Collections.Generic;
using System.Text;

namespace EKG
{
    public static class CirkularniBuffer
    {
        private static int MAX_BUFFER_SIZE = 75;
        private static double[] buffer = new double[MAX_BUFFER_SIZE];

        private static int startIndex = 0;
        private static int bufferSize = 0;

        private static object mutex = new object();


        public static bool Read(out double value)
        {
            lock (mutex)
            {
                // data available
                if (bufferSize > 0)
                {
                    value = buffer[startIndex];
                    startIndex = (startIndex + 1) % MAX_BUFFER_SIZE;
                    bufferSize--;
                    return true;
                }
                else // no data available
                {
                    value = 0;
                    Console.Write("1");
                    return false;
                }
            }
        }

        public static bool Write(double value)
        {
            lock (mutex)
            {
                if (bufferSize < MAX_BUFFER_SIZE)
                {
                    buffer[(startIndex + bufferSize) % MAX_BUFFER_SIZE] = value;
                    bufferSize++;
                    return true;
                }
                else
                {
                    Console.Write("2");
                    return false;
                }
            }
        }

        public static void Clear()
        {
            lock (mutex)
            {
                startIndex = 0;
                bufferSize = 0;
            }
        }
    }
}
